﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace FourKill.Engine
{
    public class House : IPaintable
    {
        private static House _instance;
        public static House Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new House();
                    _instance.SpriteSheet = SpriteSheets.House;
                }
                return _instance;
            }
        }

        public ISpriteSheet SpriteSheet { get; set; }

        public void Paint(IPaintableContext context)
        {
            if (context.GameObject.LocationRelativeToCamera == null)
                context.GameObject.UpdateLocation(context);
            var location = context.GameObject.LocationRelativeToCamera;

            if (location.IsVisible)
            {
                try
                {
                    if (location.ObjectRectangle.X > context.ViewPort.PixelSize.Width || location.ObjectRectangle.Y > context.ViewPort.PixelSize.Height ||
                        location.ObjectRectangle.Right < 0 || location.ObjectRectangle.Bottom < 0 ||
                        location.ObjectRectangle.Width <= 0 || location.ObjectRectangle.Height <= 0) return;

                    SpriteState spriteState = context.GameObject.Z > 0 ? SpriteState.FloatingStill : SpriteState.StandingStill;
                    if (context.GameObject.Speed > 0) spriteState = context.GameObject.Z > 0 ? SpriteState.FlyingSlow : SpriteState.Walking;

                    int fIdx = 1, fCount = this.SpriteSheet.GetFrameCount(spriteState);
                    if (fCount > 1)
                    {
                        fIdx = context.GameObject.FrameIndex + 1;
                        if (fIdx >= fCount) fIdx = 0;
                    }
                    context.GameObject.FrameIndex = fIdx;

                    context.FrontLayer.DrawImageUnscaled(
                        this.SpriteSheet.GetScaledImage(
                            location.Placement.Bearing,
                            context.GameObject.FrameIndex,
                            spriteState,
                            location.ObjectRectangle.Width,
                            location.ObjectRectangle.Height),
                        location.ObjectRectangle);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("***********************************");
                    System.Diagnostics.Debug.WriteLine(ex.Message + "\r\n" + ex.StackTrace);
                    System.Diagnostics.Debugger.Break();
                }
            }
        }
    }
}
